import NProgress from 'nprogress'
import router, {findFirstValidRoute} from './router'
import 'nprogress/nprogress.css'
import useUserStore from './stores/modules/user'
import {PageEnum} from './enums/pageEnum'
import {clearAll} from "@/utils/auth";
import {INDEX_ROUTE} from "@/router/routes";
import {isExternal} from "@/utils/validate";

// NProgress配置
NProgress.configure({showSpinner: false})

// 免登录白名单
const whiteList = [PageEnum.LOGIN, PageEnum.ERROR_403]

router.beforeEach(async (to, from, next) => {
    NProgress.start()

    const userStore = useUserStore()

    if (whiteList.includes(to.path)) {
        next()
    } else if (userStore.token) {
        if (Object.keys(userStore.userInfo).length === 0) {
            try {
                router.addRoute(INDEX_ROUTE)
                await userStore.getUserInfo()
                const routes = userStore.routes
                routes.forEach((route) => {
                    if (isExternal(route.path)) {
                        return
                    }

                    if (!route.children) {
                        router.addRoute(INDEX_ROUTE.name, route)
                        return
                    }

                    router.addRoute(route)
                })

                if (to.path === PageEnum.INDEX) {
                    const routePath = findFirstValidRoute(routes)
                    if (!routePath) {
                        clearAll()
                        next(PageEnum.ERROR_403)
                        return
                    }
                    next(routePath)
                } else {
                    next({...to, replace: true})
                }

            } catch (err) {
                clearAll()
                next({path: PageEnum.LOGIN, query: {redirect: to.fullPath}})
            }

        } else {
            next()
        }
    } else {
        next({path: PageEnum.LOGIN, query: {redirect: to.fullPath}})
    }
})
router.afterEach(() => {
    NProgress.done()
})
